package com.base.action;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.util.FileCopyUtils;

import com.common.bean.Personnel;
import com.common.exception.SystemException;
import com.common.util.PagerModel;

public class PersonnelListAction extends PersonnelAbstractManagerAction {

	private static final long serialVersionUID = 5856298809065683771L;

	private Personnel personnel;

	private String staffcode;

	private List<Personnel> personnellist;

	private PagerModel pm;

	@SuppressWarnings("unchecked")
	@Override
	public String execute() throws Exception {
		int offset = 0;
		int pagesize = 10;

		try {
			offset = Integer
					.parseInt(ServletActionContext.getRequest().getParameter("pager.offset"));
		} catch (Exception e) {
		}

		// personnellist = personnelService.findAllPersonnels();
		pm = personnelService.findPersonnels(offset, pagesize);
		return SUCCESS;
	}

	public String findPersonnel() {
		personnel = personnelService.findPersonnel(staffcode);
		return SUCCESS;
	}

	public String removePersonnel() {
		personnelService.removePersonnel(staffcode);
		return SUCCESS;
	}

	public String findBlobDataPer() throws Exception {
		HttpServletResponse response = null;
		ServletOutputStream out = null;
		InputStream in = null;
		personnel = personnelService.findPersonnel(staffcode);

		if (personnel == null) {
			throw new SystemException("没有这个人！");
		}

		try {
			response = ServletActionContext.getResponse();
			response.setContentType("image/jpeg");
			out = response.getOutputStream();
			Blob blob = personnel.getPhoto();
			in = blob.getBinaryStream();

			FileCopyUtils.copy(in, out);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return null;
	}

	public Personnel getPersonnel() {
		return personnel;
	}

	public void setPersonnel(Personnel personnel) {
		this.personnel = personnel;
	}

	public List<Personnel> getPersonnellist() {
		return personnellist;
	}

	public void setPersonnellist(List<Personnel> personnellist) {
		this.personnellist = personnellist;
	}

	public String getStaffcode() {
		return staffcode;
	}

	public void setStaffcode(String staffcode) {
		this.staffcode = staffcode;
	}

	public PagerModel getPm() {
		return pm;
	}

	public void setPm(PagerModel pm) {
		this.pm = pm;
	}

}
